/**
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为www.tonetn.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package com.xunyin.modules.shareorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.xunyin.api.XunyinException;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.enums.*;
import com.xunyin.modules.couponnew.domain.MtUserCoupon;
import com.xunyin.modules.couponnew.service.mapper.MtUserCouponMapper;
import com.xunyin.modules.device.domain.TDevice;
import com.xunyin.modules.device.service.mapper.TDeviceMapper;
import com.xunyin.modules.log.domain.TCleaningRecord;
import com.xunyin.modules.log.domain.TimelongRecord;
import com.xunyin.modules.log.service.mapper.TCleaningRecordMapper;
import com.xunyin.modules.log.service.mapper.TimelongRecordMapper;
import com.xunyin.modules.maincouponsend.service.mapper.TmainCouponUserMapper;
import com.xunyin.modules.membersuser.domain.TMembersUser;
import com.xunyin.modules.membersuser.service.mapper.TMembersUserMapper;
import com.xunyin.modules.membersuser.vo.MemberUserVo;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.domain.MtStoreRoom;
import com.xunyin.modules.mtstore.service.MtStoreRoomService;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.mtstore.service.mapper.MtStoreRoomMapper;
import com.xunyin.modules.mtuserbalance.domain.MtUserBalance;
import com.xunyin.modules.mtuserbalance.service.MtUserBalanceService;
import com.xunyin.modules.mtusergrade.domain.MtUserGrade;
import com.xunyin.modules.mtusergrade.service.mapper.MtUserGradeMapper;
import com.xunyin.modules.recharge.domain.TRechargeOrder;
import com.xunyin.modules.recharge.domain.TRechargeSet;
import com.xunyin.modules.recharge.service.mapper.TRechargeOrderMapper;
import com.xunyin.modules.recharge.service.mapper.TRechargeSetMapper;
import com.xunyin.modules.redisqueue.PublishMessage;
import com.xunyin.modules.redisqueue.RedisSqueueService;
import com.xunyin.modules.shareorder.bo.OrderDateHour;
import com.xunyin.modules.shareorder.domain.TShareOrder;
import com.xunyin.modules.shareorder.param.TShareOrderParam;
import com.xunyin.modules.shareorder.service.TShareOrderService;
import com.xunyin.modules.shareorder.service.dto.OrderStatDto;
import com.xunyin.modules.shareorder.service.dto.ShareCountDto;
import com.xunyin.modules.shareorder.service.dto.ShareOrderCountDto;
import com.xunyin.modules.shareorder.service.dto.TShareOrderQueryCriteria;
import com.xunyin.modules.shareorder.service.mapper.TShareOrderMapper;
import com.xunyin.modules.shareorder.vo.TShareOrderForSwitchVo;
import com.xunyin.modules.shareorder.vo.TShareOrderVo;
import com.xunyin.modules.store.domain.TStore;
import com.xunyin.modules.store.service.TStoreService;
import com.xunyin.modules.storeroom.service.TStoreRoomService;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.SysXbuserService;
import com.xunyin.modules.user.service.YxUserService;
import com.xunyin.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author admin
 * @date 2022-09-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
//@CacheConfig(cacheNames = "tShareOrder")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TShareOrderServiceImpl extends BaseServiceImpl<TShareOrderMapper, TShareOrder> implements TShareOrderService {

    private final IGenerator generator;

    @Autowired
    private TShareOrderMapper tShareOrderMapper;

    @Autowired
    private MtStoreRoomMapper mtStoreRoomMapper;

    @Autowired
    private TDeviceMapper tDeviceMapper;

    @Autowired
    private TStoreService tStoreService;

    @Autowired
    private YxUserService userService;

    /**
     * 店铺服务接口
     */
    @Autowired
    private StoreService storeService;

    @Autowired
    private MtStoreRoomService mtStoreRoomService;

    @Autowired
    private TStoreRoomService tStoreRoomService;

    @Autowired
    private TmainCouponUserMapper tmainCouponUserMapper;

    @Autowired
    private MtUserCouponMapper mtUserCouponMapper;

    @Autowired
    private TimelongRecordMapper timelongRecordMapper;

    @Autowired
    private TMembersUserMapper tMembersUserMapper;

    @Autowired
    private TRechargeSetMapper tRechargeSetMapper;

    @Autowired
    private TRechargeOrderMapper tRechargeOrderMapper;

    @Autowired
    private TCleaningRecordMapper tCleaningRecordMapper;

    @Autowired
    private MtUserBalanceService mtUserBalanceService;

    @Autowired
    private SysXbuserService sysXbuserService;

    @Autowired
    private MtUserGradeMapper mtUserGradeMapper;

    @Autowired
    private RedisSqueueService redisSqueueService;

    @Value("${project.tea.server}")
    private String projectTeaServer;

    @Value("${project.pay.server}")
    private String projectPayServer;

    @Value("${tuya.url}")
    private String tuyaUrl;

    @Value("${tuya.client_id}")
    private String tuyaClientId;

    @Value("${tuya.client_secret}")
    private String tuyaClientSecret;


    @Override
    public JSONObject getOrderInfo(JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        TShareOrder teaOrder = tShareOrderMapper.selectById(id);
        return CommonUtil.successJson(teaOrder);
    }

    public static void main(String[] args) {

        String teaServerTime = "2023-10-29 16:30~2023-10-29 18:30";
        String[] teaServerTimeArr = teaServerTime.split("~");
        String startTimeStr = teaServerTimeArr[0];
        String endTimeStr = teaServerTimeArr[1];
        String startDateStr = startTimeStr.substring(5,10);
        String endDateStr = endTimeStr.substring(5,10);
        String startHour = startTimeStr.substring(11,13);
        String endHourMin = endTimeStr.substring(11,16);
        if(startHour.substring(0,1).equals("0")){
            startHour = startHour.substring(1);
        }
        String endHour = endTimeStr.substring(11,13);
        if(endHour.substring(0,1).equals("0")){
            endHour = endHour.substring(1);
        }
        Integer startHourInt = Integer.parseInt(startHour);
        Integer endHourInt = Integer.parseInt(endHour);

        System.out.println("startDateStr:"+startDateStr);
        System.out.println("endDateStr:"+endDateStr);
        System.out.println("startHourInt:"+startHourInt);
        System.out.println("endHourInt:"+endHourInt);
        System.out.println("endHourMin:"+endHourMin);

    }

    /**
     * 预约时间单内订单已使用查询接口V2
     * @param tShareOrderParam
     * @return
     */
    @Override
    public List<OrderDateHour> getTimeListOrderV2(TShareOrderParam tShareOrderParam){

        // Map<String, Object> data = new HashMap();
        String startTime = DateUtils.parseDate2String(new Date(), "yyyy-MM-dd HH:mm") + ":00";
        Date endDate = DateUtil.addDate(new Date(), Calendar.DATE, 7);
        String endTime = DateUtils.parseDate2String(endDate, "yyyy-MM-dd") + " 24:00:00";
        Integer teaChildId = tShareOrderParam.getTeaChildId();
        // 根据查询订单，获取每个日期及包括已预定的小时数
        List<TShareOrder> list = tShareOrderMapper.getTimeListOrder(startTime, endTime, teaChildId);
        // 日期dateMap
        //Map<String, List<Integer>> dateMap = new HashMap();
        Map<String, OrderDateHour> dateMap = new HashMap();
        List<OrderDateHour> orderDateHourList = new ArrayList<>();
        // list -> bean-(date,小时list)
        if (list.size() == 0) {

            //return dateMap;
            return orderDateHourList;

        }else{

            for (int i = 0; i < list.size(); i++) {

                String teaServerTime = list.get(i).getTeaServerTime();
                String[] teaServerTimeArr = teaServerTime.split("~");
                String startTimeStr = teaServerTimeArr[0];
                String endTimeStr = teaServerTimeArr[1];
                String startDateStr = startTimeStr.substring(5,10);
                String endDateStr = endTimeStr.substring(5,10);
                String startHour = startTimeStr.substring(11,13);
                String endHourMin = endTimeStr.substring(11,16);
                if(startHour.substring(0,1).equals("0")){
                    startHour = startHour.substring(1);
                }
                String endHour = endTimeStr.substring(11,13);
                if("00".equals(endHour)){
                    endHour = "24";
                }
                if(endHour.substring(0,1).equals("0")){
                    endHour = endHour.substring(1);
                }
                Integer startHourInt = Integer.parseInt(startHour);
                Integer endHourInt = Integer.parseInt(endHour);

                Boolean isExistFlag = false;
                OrderDateHour orderDateHour = new OrderDateHour();
                // 同一天订单
                if(startDateStr.equals(endDateStr)){

                    // 根据日期判断是否存在，如果存在则累加，没存在则新增
/*                    Set<String> keyList = dateMap.keySet();
                    for (String item : keyList) {
                        if(item.equals(startDateStr)){
                            isExistFlag = true;
                        }
                    }*/
                    int isExistIndex = 0;
                    for (OrderDateHour item : orderDateHourList){

                        if(item.getOrderDate().equals(startDateStr)){
                            orderDateHour = item;
                            isExistFlag = true;
                            break;
                        }
                        isExistIndex++;
                    }

                    List<Integer> hourList = new ArrayList<>();

                    if(isExistFlag){

                        //hourList = dateMap.get(startDateStr);
                        //hourList = dateMap.get(startDateStr).getHourList();
                        hourList = orderDateHour.getHourList();

                    // 日期不存在，则添加
                    }else{

                    }

                    for (int hour = startHourInt; hour <= endHourInt; hour++) {

                        hourList.add(hour);
                    }

                    // 添加日期及日期的小时数
                    orderDateHour.setOrderDate(startDateStr);
                    orderDateHour.setHourList(hourList);
                    Integer maxHour = getMax(hourList);
                    if(endHourInt.equals(maxHour)){
                        // 改添加结束时间包括分钟
                        orderDateHour.setMaxOrderHourMin(endHourMin);
                    }
                    // 如果已存在，则覆盖
/*                    if(isExistFlag){
                        orderDateHourList.add(isExistIndex,orderDateHour);
                    // 不存在，新增
                    }else{
                        orderDateHourList.add(orderDateHour);
                    }*/
                    orderDateHourList.add(orderDateHour);
                    //orderDateHourList.remove();
                    //dateMap.put(startDateStr,orderDateHour);
                    //orderDateHourList.add(orderDateHour);

                // 隔天订单
                }else{

                    // 开始时间到24
                    // 根据日期判断是否存在，如果存在则累加，没存在则新增
/*                    Set<String> keyList = dateMap.keySet();
                    for (String item : keyList) {
                        if(item.equals(startDateStr)){
                            isExistFlag = true;
                        }
                    }*/
                    int isExistIndex = 0;
                    for (OrderDateHour item : orderDateHourList){

                        if(item.getOrderDate().equals(startDateStr)){
                            orderDateHour = item;
                            isExistFlag = true;
                            break;
                        }
                        isExistIndex++;
                    }

                    List<Integer> hourList = new ArrayList<>();

                    if(isExistFlag){
                        //hourList = dateMap.get(startDateStr).getHourList();
                        hourList = orderDateHour.getHourList();
                    }
                    for (int hour = startHourInt; hour <= 24; hour++) {
                        hourList.add(hour);
                    }

                    // 添加日期及日期的小时数
                    orderDateHour.setOrderDate(startDateStr);
                    orderDateHour.setHourList(hourList);
                    //Integer maxHour = getMax(hourList);
                    //if(maxHour==endHourInt){
                        // 改添加结束时间包括分钟
                        orderDateHour.setMaxOrderHourMin("24:00");
                    //}
                    // 如果已存在，则覆盖
/*                    if(isExistFlag){
                        orderDateHourList.add(isExistIndex,orderDateHour);
                        // 不存在，新增
                    }else{
                        orderDateHourList.add(orderDateHour);
                    }*/
                    orderDateHourList.add(orderDateHour);

                    //dateMap.put(startDateStr,orderDateHour);

                    // 结束时间从0到结束时间
                    orderDateHour = new OrderDateHour();
                    isExistFlag = false;
/*                    keyList = dateMap.keySet();
                    for (String item : keyList) {
                        if(item.equals(endDateStr)){
                            isExistFlag = true;
                        }
                    }*/
                    isExistIndex = 0;
                    for (OrderDateHour item : orderDateHourList){

                        if(item.getOrderDate().equals(endDateStr)){
                            orderDateHour = item;
                            isExistFlag = true;
                            break;
                        }
                        isExistIndex++;
                    }


                    hourList = new ArrayList<>();
                    if(isExistFlag){
                        //hourList = dateMap.get(endDateStr);
                        hourList = orderDateHour.getHourList();
                    }

                    for (int hour = 0; hour <= endHourInt; hour++) {
                        hourList.add(hour);
                    }

                    //dateMap.put(endDateStr,hourList);
                    orderDateHour.setOrderDate(endDateStr);
                    orderDateHour.setHourList(hourList);
                    Integer maxHour = getMax(hourList);
                    if(maxHour.equals(endHourInt)){
                        // 改添加结束时间包括分钟
                        orderDateHour.setMaxOrderHourMin(endHourMin);
                    }
                    // 如果已存在，则覆盖
/*                    if(isExistFlag){
                        orderDateHourList.add(isExistIndex,orderDateHour);
                    // 不存在，新增
                    }else{
                        orderDateHourList.add(orderDateHour);
                    }*/
                    orderDateHourList.add(orderDateHour);

                    //dateMap.put(endDateStr,orderDateHour);
                }
            }
        }

        return orderDateHourList;
    }

    public Integer getMax(List<Integer> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        int max = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) > max) {
                max = list.get(i);
            }
        }
        return max;
    }

    /**
     * 预约时间单内订单已使用查询接口
     * @param tShareOrderParam
     * @return
     */
    @Override
    public Map<String, Object> getTimeListOrder(TShareOrderParam tShareOrderParam) {

        //String startTime = jsonObject.getString("startTime");
        //String endTime = jsonObject.getString("endTime");
        //Integer teaChildId = jsonObject.getInteger("teaChildId");
        Map<String, Object> data = new HashMap();
        String startTime = DateUtils.parseDate2String(new Date(), "yyyy-MM-dd HH:mm") + ":00";
        Date endDate = DateUtil.addDate(new Date(), Calendar.DATE, 7);
        //String startTime = tShareOrderParam.getStartTime();
        String endTime = DateUtils.parseDate2String(endDate, "yyyy-MM-dd") + " 24:00:00";
        //String endTime = tShareOrderParam.getEndTime();

        Integer teaChildId = tShareOrderParam.getTeaChildId();
        List<TShareOrder> list = tShareOrderMapper.getTimeListOrder(startTime, endTime, teaChildId);
        if (list.size() == 0) {
            data.put("timeList", new JSONArray());
            //return CommonUtil.successJson();
        } else {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                JSONObject jSONObject = JSONObject.parseObject(list.get(i).getTeaSubscribeTimes());
                jsonArray.add(jSONObject);
                //JSONArray array = JSONArray.parseArray(list.get(i).getTeaSubscribeTimes());
                //jsonArray.addAll(array);
            }
            data.put("timeList", jsonArray);
            //return CommonUtil.successJson(jsonArray);
        }
        return data;

    }



    /**
     * 订单信息
     *
     * @param unique 唯一值或者单号
     * @param uid    用户id
     * @return YxStoreOrderQueryVo
     */
    @Override
    public TShareOrderVo getOrderInfo(String unique, Long uid) {
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.eq(TShareOrder::getAppOrderNo, unique));
        if (uid != null) {
            wrapper.eq(TShareOrder::getAppUserId, uid);
        }
        return generator.convert(tShareOrderMapper.selectOne(wrapper), TShareOrderVo.class);
    }

    @Override
    public TShareOrder selectByAppOrderNo(String orderId) {
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.eq(TShareOrder::getAppOrderNo, orderId));
        wrapper.and(i -> i.eq(TShareOrder::getStatus, 1));
        return tShareOrderMapper.selectOne(wrapper);
    }

    @Override
    public TShareOrder selectById(Integer id) {
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.eq(TShareOrder::getId, id));
        wrapper.and(i -> i.eq(TShareOrder::getStatus, 1));
        return tShareOrderMapper.selectOne(wrapper);
    }

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(TShareOrderQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<TShareOrder> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<TShareOrder> queryAll(TShareOrderQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(TShareOrder.class, criteria));
    }

    /**
     * 获取订单统计数据
     * @return OrderStatDto
     */
    @Override
    public OrderStatDto getOrderStat(Integer storeId) {
        OrderStatDto orderStatDto = new OrderStatDto();
        orderStatDto.setSumOrderMoney(tShareOrderMapper.sumOrderMoney(storeId));
        if (storeId == 0) {
            storeId = null;
        }
        orderStatDto.setSumRealOrderMoney(tShareOrderMapper.sumRealOrderMoney(storeId));
        return orderStatDto;
    }

    /**
     * 获取订单统计数据(根据选择天数)
     * @return OrderStatDto
     */
    @Override
    public OrderStatDto getOrderStatByDayNum(Integer storeId,Integer dayNum) {

        OrderStatDto orderStatDto = new OrderStatDto();
        //orderStatDto.setSumOrderMoney(tShareOrderMapper.sumOrderMoney());
        if (storeId == 0) {
            storeId = null;
        }
        orderStatDto.setSumOrderMoney(tShareOrderMapper.sumOrderMoneyByDayNum(storeId,dayNum));
        orderStatDto.setSumRealOrderMoney(tShareOrderMapper.sumRealOrderMoneyByDayNum(storeId,dayNum));
        orderStatDto.setOrderCount(tShareOrderMapper.sumOrderCountByDayNum(storeId,dayNum));

        return orderStatDto;
    }



    /**
     * 用户全部状态的订单列表
     * 根据用户id获取用户全部状态的订单列表
     * @param tShareOrderParam
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> getOrderListByUserId(TShareOrderParam tShareOrderParam) {
        List<TShareOrderVo> list = tShareOrderMapper.orderList(tShareOrderParam.getUserId(), tShareOrderParam.getOrderStatus(), null);
        return list;
    }


    /**
     * 已完成的订单列表
     * 根据用户id获取已完成的订单列表
     * @param userId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> successOrder(Integer userId) {
        List<TShareOrderVo> list = tShareOrderMapper.orderList(userId, 4, null);
        return list;
    }

    /**
     * 待付款的订单列表
     * 根据用户id获取待付款的订单列表
     * @param userId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> toBePaidOrder(Integer userId) {
        List<TShareOrderVo> list = tShareOrderMapper.orderList(userId, 0, null);
        return list;
    }

    /**
     * 待使用的订单列表
     * 根据用户id获取待使用的订单列表
     * @param userId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> toUseOrder(Integer userId) {
        Date date = new Date();
        List<TShareOrderVo> list = tShareOrderMapper.orderList(userId, 1, date);
        return list;
    }

    /**
     * 使用中的订单列表
     * 根据用户id获取使用中的订单列表
     * @param userId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> inUseOrder(Integer userId) {
        List<TShareOrderVo> list = tShareOrderMapper.orderList(userId, 2, null);
        return list;
    }

    /**
     * 使用中的订单列表
     * 根据用户id获取使用中的订单列表
     * @param storeRoomId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> orderListByRoomId(Integer storeRoomId) {
        List<TShareOrderVo> list = tShareOrderMapper.orderListByRoomId(storeRoomId, 2);
        return list;
    }


    /**
     * 已取消的订单列表
     * 根据用户id获取已取消的订单列表
     * @param userId
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> cancelOrder(Integer userId) {
        List<TShareOrderVo> list = tShareOrderMapper.orderList(userId, 3, null);
        return list;
    }

    /**
     * 取消订单 (新版本 卡券处理待修改)
     *   没用到
     * @param tShareOrderParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelOrderPay(TShareOrderParam tShareOrderParam) {
        log.debug("取消订单");
        Integer orderId = tShareOrderParam.getOrderId();
        Integer userId = tShareOrderParam.getUserId();
        Date nowDate = new Date();
        TShareOrder teaOrder = tShareOrderMapper.selectById(orderId);
        //判断订单表状态(已付款15分钟前可取消)
        boolean flag = false;
        if (teaOrder.getOrderStatus() == 1) {
            //当前时间小于预约开始时间
            if (teaOrder.getTeaServerStartTime().getTime() > nowDate.getTime()) {
                long newTime = nowDate.getTime();
                long TeaServerStartTime = teaOrder.getTeaServerStartTime().getTime();
                long out = (TeaServerStartTime - newTime) / 1000;
//                int orderTimeLong = DateUtil.getDateDiffLong(nowDate, teaOrder.getTeaServerStartTime());
//                if (Math.abs(orderTimeLong-0)>1800) {
                if (out > 900) {
                    TShareOrder order = new TShareOrder();
                    //取消订单-有付金额进行退款，没有付金额进行返券
                    if (teaOrder.getPayMoney().compareTo(new BigDecimal(0)) > 0) {
                        //退款
                        //退款后更新订单退款状态
                        //refundOrder(teaOrder);
                        //weixinPayService.refundOrder(teaOrder);

                    } else {
                        order.setId(teaOrder.getId());
                        order.setServiceStatus(5);
                        order.setOrderStatus(3);
                        order.setUpdateUserId(userId);
                        order.setUpdateTime(nowDate);

                        tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                                .eq(TShareOrder::getId, teaOrder.getId()));

                        //返回抵扣的免费时长
                        MemberUserVo memberUserVo = tMembersUserMapper.selectByTransPhoneAndMainId(teaOrder.getUserPhone(), teaOrder.getMainId());

                        TMembersUser teaMembersUser = new TMembersUser();
                        cn.hutool.core.bean.BeanUtil.copyProperties(memberUserVo, teaMembersUser);
                        teaMembersUser.setUpdateTime(new Date());
                        BigDecimal returnTotalTime = teaMembersUser.getMembersTimeLength().add(teaOrder.getDeductTimelong());
                        teaMembersUser.setMembersTimeLength(returnTotalTime);

                        tMembersUserMapper.update(teaMembersUser, Wrappers.<TMembersUser>lambdaQuery()
                                .eq(TMembersUser::getId, teaMembersUser.getId()));

                        //记录时长退还日志
                        if (teaOrder.getDeductTimelong().compareTo(BigDecimal.ZERO) > 0) {
                            //if (teaOrder.getDeductTimelong() > 0) {
                            TimelongRecord timelongRecord = new TimelongRecord();
                            timelongRecord.setMainId(teaOrder.getMainId());
                            timelongRecord.setSource(4);
                            timelongRecord.setTimelong(teaOrder.getDeductTimelong());
                            timelongRecord.setGiver(0);
                            timelongRecord.setRecipient(teaOrder.getMemberUserId());
                            timelongRecord.setOrderNo(teaOrder.getOrderNo());
                            timelongRecord.setRemark("订单退款-全部使用时长");
                            timelongRecord.setCreateUserId(teaOrder.getCreateUserId());
                            timelongRecord.setCreateTime(new Date());
                            timelongRecord.setStatus(Short.parseShort("1"));
                            timelongRecordMapper.insert(timelongRecord);
                        }
                        //返回抵扣优惠券

                    }

                    flag = true;
                } else {
                    flag = false;

                }
            }
        }
        return flag;
    }


    /**
     * 发起退款  (新版本 卡券处理待修改)
     *
     * @param
     */
    public String refundOrder(TShareOrder teaOrder) {
        log.info("=====退款回调=====");
        Date date = new Date();

        //生成退款单号
        String refundNo = OrderNoUtil.getOrderNo("refu", "");

        Integer handleStatus = 1;

        //修改临时订单状态
        TShareOrder order = new TShareOrder();
        order.setId(teaOrder.getId());
        order.setRefundOrderNo(refundNo);
        order.setRefundMoney(teaOrder.getPayMoney());
        //0-不退款；1-退款中；2-已退款
        order.setReturnFlag(handleStatus);
        order.setServiceStatus(5);
        order.setOrderStatus(OrderStatusEnum.CANCELLED.getIndex());
        order.setUpdateTime(date);
        order.setUpdateUserId(teaOrder.getCreateUserId());
        tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                .eq(TShareOrder::getId, teaOrder.getId()));
        //微信支付完成回调地址
        try {

            String url = projectPayServer + "/refund/manager/wechat/refundApply";
            String outNotifyUrl = projectTeaServer + "/miniapi/order/refundNotify";

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("outOrderNo", teaOrder.getAppOrderNo());
            jsonObject.put("outRefundNo", refundNo);
            jsonObject.put("refundMoney", teaOrder.getPayMoney());
            jsonObject.put("outNotifyUrl", outNotifyUrl);
            jsonObject.put("appNo", "xbxc");
            jsonObject.put("functionNo", "xc");
            log.debug("refundOrder=======================:" + jsonObject.toString());

            String returnResult = HttpClientUtil.doPostJson(url, jsonObject.toString());
            JSONObject baseResult = com.alibaba.fastjson.JSON.parseObject(returnResult, JSONObject.class);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }


    /**
     * 首页续单接口
     * 根据用户id获取当前正在使用的订单列表
     * @param tShareOrderParam
     * @return List<TShareOrderVo>
     */
    @Override
    public List<TShareOrderVo> repeatOrder(TShareOrderParam tShareOrderParam) {
        Date date = new Date();
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        Boolean endTimeIsTwentyFour = false;
        // 表示订单页面点具体一个订单的续单接口
        if (tShareOrderParam.getOrderId() > 0) {
            wrapper.eq(TShareOrder::getId, tShareOrderParam.getOrderId());

            //  先查询这订单信息
            TShareOrder tShareOrder = tShareOrderMapper.selectById(tShareOrderParam.getOrderId());
            long serverEndTime = tShareOrder.getTeaServerEndTime().getTime();
            String teaServerEndTime = DateUtil.parseDate2String(tShareOrder.getTeaServerEndTime(), "yyyy-MM-dd HH:mm");
            long now = (new Date()).getTime();
            // 获取结束时间是否00:00:00，如果“是”
            if(teaServerEndTime.contains("00:00")){

                endTimeIsTwentyFour = true;
                // 不查数据库，当前时间跟24:00 比，是否小于，如果小于，则不加getTeaServerEndTime条件查询
                teaServerEndTime = teaServerEndTime.substring(0,11)+"24:00";
                serverEndTime = DateUtils.parseStrint2Date(teaServerEndTime, "yyyy-MM-dd HH:mm").getTime();
                long serverEndTimeDiff = (serverEndTime - now) / 1000 / 60;

                // 表示订单没还结束，则不加getTeaServerEndTime条件查询
                // 表示订单已结束,直接返回
                if (serverEndTimeDiff < 0) {
                    List<TShareOrderVo> list = new ArrayList<>();
                    return list;
                }
            }

            // 如果"不是" 默认endTimeIsTwentyFour = false,加getTeaServerEndTime条件查询
        }

        // 表示开门操作，查询服务中的订单
        if (tShareOrderParam.getOperFlag() == 1) {

            if(endTimeIsTwentyFour){

                wrapper.eq(TShareOrder::getCreateUserId, tShareOrderParam.getUserId())
                        .eq(TShareOrder::getStatus, 1)
                        .eq(TShareOrder::getOrderStatus, 2);
            }else{

                wrapper.eq(TShareOrder::getCreateUserId, tShareOrderParam.getUserId())
                        .gt(TShareOrder::getTeaServerEndTime, date)
                        .eq(TShareOrder::getStatus, 1)
                        .eq(TShareOrder::getOrderStatus, 2)
                        .orderByAsc(TShareOrder::getTeaServerEndTime);
            }


        // 表示续单操作，查询支付的订单，服务中的订单
        } else {

            if(endTimeIsTwentyFour) {

                wrapper.eq(TShareOrder::getCreateUserId, tShareOrderParam.getUserId())
                        .eq(TShareOrder::getStatus, 1)
                        .and(wq -> wq
                                .eq(TShareOrder::getOrderStatus, 1)
                                .or()
                                .eq(TShareOrder::getOrderStatus, 2));
            }else{

                wrapper.eq(TShareOrder::getCreateUserId, tShareOrderParam.getUserId())
                        .gt(TShareOrder::getTeaServerEndTime, date)
                        .eq(TShareOrder::getStatus, 1)
                        .and(wq -> wq
                                .eq(TShareOrder::getOrderStatus, 1)
                                .or()
                                .eq(TShareOrder::getOrderStatus, 2))
                        .orderByAsc(TShareOrder::getTeaServerEndTime);
            }

        }



/*        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TShareOrder::getCreateUserId, userId)
                .eq(TShareOrder::getStatus, 1)
                .gt(TShareOrder::getTeaServerEndTime, date)
                .eq(TShareOrder::getOrderStatus, "2").orderByAsc(TShareOrder::getTeaServerEndTime);*/


        List<TShareOrderVo> list = generator.convert(baseMapper.selectList(wrapper), TShareOrderVo.class);
        return list;
    }

    /**
     * 保洁人员订单管理-接口
     * @param storeId
     * @return
     */
    @Override
    public List<TShareOrderVo> loadTeaHouseOrder4Manage(Integer storeId, Integer orderStatus,Integer dayNum) {
        List<TShareOrderVo> list = tShareOrderMapper.loadTeaHouseOrder4Manage(storeId, orderStatus,dayNum);
        return list;
    }

    /**
     * 管理人员查询预约订单关联保洁记录管理-接口
     * @param storeId
     * @return
     */
    @Override
    public List<TShareOrderVo> loadTeaHouseOrder4ManageByCleaningRecord(Integer storeId, Integer orderStatus,Integer dayNum) {
        List<TShareOrderVo> list = tShareOrderMapper.loadTeaHouseOrder4ManageByCleaningRecord(storeId, orderStatus,dayNum);
        return list;
    }




    /**
     * 订单页面续单接口
     * 根据用户id获取当前正在使用的订单
     * @param tShareOrderParam
     * @return TShareOrderVo
     */
    @Override
    public TShareOrderVo repeatOrderList(TShareOrderParam tShareOrderParam) {
        Date date = new Date();
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TShareOrder::getCreateUserId, tShareOrderParam.getUserId())
                .eq(TShareOrder::getId, tShareOrderParam.getId())
                .gt(TShareOrder::getTeaServerEndTime, date)
                .eq(TShareOrder::getStatus, 1).and(wq -> wq
                .eq(TShareOrder::getOrderStatus, 1)
                .or()
                .eq(TShareOrder::getOrderStatus, 2)).orderByAsc(TShareOrder::getTeaServerEndTime);
        TShareOrderVo tShareOrderVo = generator.convert(baseMapper.selectOne(wrapper), TShareOrderVo.class);
        return tShareOrderVo;
    }


    /**
     * 根据门店Id、房间Id,获取房间的大门、房间智能开关
     * @param tShareOrderParam
     * @return List<TShareOrderForSwitchVo>
     */
    @Override
    public List<TShareOrderForSwitchVo> getStoreRoomDevice(TShareOrderParam tShareOrderParam) {

        LambdaQueryWrapper<TDevice> wrapper1 = new LambdaQueryWrapper<>();

        wrapper1.eq(TDevice::getStoreId, tShareOrderParam.getStoreId())
                .eq(TDevice::getStatus, 1)
                .eq(TDevice::getDeviceStatus, 1);

        wrapper1.and(i -> i.eq(TDevice::getStoreRoomId, tShareOrderParam.getStoreRoomId())
                .or().eq(TDevice::getStoreRoomId, 0));

        wrapper1.and(i -> i.eq(TDevice::getDeviceType, 0)
                .or().eq(TDevice::getDeviceType, 1)
                .or().eq(TDevice::getDeviceType, 4)
                .or().eq(TDevice::getDeviceType, 5));

        wrapper1.orderByAsc(TDevice::getDeviceType);
        JSONObject deviceKeyCache = new JSONObject();
        List<TShareOrderForSwitchVo> tShareOrderForSwitchVos = new ArrayList<>();
        List<TDevice> devices = tDeviceMapper.selectList(wrapper1);
        for (TDevice device : devices) {
            if (deviceKeyCache.containsKey(device.getDeviceNo())) {
                continue;
            }
            TShareOrderForSwitchVo tShareOrderForSwitchVo = new TShareOrderForSwitchVo();
            tShareOrderForSwitchVo.setDevicePos(device.getDevicePos());
/*            tShareOrderForSwitchVo.setTeaServerTime(tShareOrder.getTeaServerTime());
            tShareOrderForSwitchVo.setTeaHouseName(tShareOrder.getStoreName());
            tShareOrderForSwitchVo.setTeaChildId(tShareOrder.getStoreRoomId());
            tShareOrderForSwitchVo.setTeaChildName(tShareOrder.getStoreRoomName());*/
            tShareOrderForSwitchVo.setSwitchId(device.getId());
            tShareOrderForSwitchVo.setSwitchName(device.getDeviceName());
            //tShareOrderForSwitchVo.setOrderId(tShareOrder.getId());
            tShareOrderForSwitchVo.setDeviceType(device.getDeviceType());
            deviceKeyCache.put(device.getDeviceNo(), true);
            tShareOrderForSwitchVos.add(tShareOrderForSwitchVo);

        }
        return tShareOrderForSwitchVos;
    }

    /**
     * 首页单个订单开门码调用接口
     * 根据用户id获取订单二维码
     * @param userId
     * @return List<TShareOrderForSwitchVo>
     */
    @Override
    public List<TShareOrderForSwitchVo> getOrderQrCode(Integer userId) {

        Date date = new Date();
        LambdaQueryWrapper<TShareOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TShareOrder::getCreateUserId, userId)
                .eq(TShareOrder::getStatus, 1)
                .gt(TShareOrder::getTeaServerEndTime, date)
                .eq(TShareOrder::getOrderStatus, 2).orderByAsc(TShareOrder::getTeaServerEndTime);
        List<TShareOrder> list = baseMapper.selectList(wrapper);

        JSONObject deviceKeyCache = new JSONObject();
        List<TShareOrderForSwitchVo> tShareOrderForSwitchVos = new ArrayList<>();
        for (TShareOrder tShareOrder : list) {
            // 获取订单相关联的门店大门设备与包间门设备，小程序前端进行开门操作
            LambdaQueryWrapper<TDevice> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(TDevice::getStoreId, tShareOrder.getStoreId())
                    //.eq(TDevice::getStoreRoomId, tShareOrder.getStoreRoomId())
                    .eq(TDevice::getStatus, 1)
                    .eq(TDevice::getDeviceStatus, 1);
            // 后台添加门店大门设备时，没有包间Id设置，默认为空
/*            lambdaQueryWrapper .and(wq -> wq
                    .gt(EtStuWarning::getNotSignNum, 2)
                    .or()
                    .gt(EtStuWarning::getNotTestNum,0));*/
            wrapper1.and(i -> i.eq(TDevice::getStoreRoomId, tShareOrder.getStoreRoomId()).or().eq(TDevice::getStoreRoomId, 0));
            wrapper1.and(i -> i.eq(TDevice::getDeviceType, 0).or().eq(TDevice::getDeviceType, 1));
            wrapper1.orderByAsc(TDevice::getDeviceType);
            List<TDevice> devices = tDeviceMapper.selectList(wrapper1);
            for (TDevice device : devices) {
/*                if (device.getDeviceType() != 0 || deviceKeyCache.containsKey(device.getDeviceNo())) {
                    continue;
                }*/
                if (deviceKeyCache.containsKey(device.getDeviceNo())) {
                    continue;
                }
                TShareOrderForSwitchVo tShareOrderForSwitchVo = new TShareOrderForSwitchVo();
                tShareOrderForSwitchVo.setTeaServerTime(tShareOrder.getTeaServerTime());
                tShareOrderForSwitchVo.setTeaHouseName(tShareOrder.getStoreName());
                tShareOrderForSwitchVo.setTeaChildId(tShareOrder.getStoreRoomId());
                tShareOrderForSwitchVo.setTeaChildName(tShareOrder.getStoreRoomName());
                tShareOrderForSwitchVo.setSwitchId(device.getId());
                tShareOrderForSwitchVo.setSwitchName(device.getDeviceName());
                tShareOrderForSwitchVo.setOrderId(tShareOrder.getId());
                tShareOrderForSwitchVo.setDeviceType(device.getDeviceType());
                deviceKeyCache.put(device.getDeviceNo(), true);
                tShareOrderForSwitchVos.add(tShareOrderForSwitchVo);
            }
        }
        return tShareOrderForSwitchVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TShareOrder> createOrder(TShareOrderParam tShareOrderParam) {
        log.info("下单请求参数：", JSONObject.toJSONString(tShareOrderParam));
        Date nowDate = new Date();
        List<TShareOrder> shareOrderList = new ArrayList<>();
        //try {
        int teaId = tShareOrderParam.getTeaId();
        String appUserId = tShareOrderParam.getAppUserId();
        int teaChildId = tShareOrderParam.getTeaChildId();
        //String times = tShareOrderParam.getTimes();
        String serverTime = tShareOrderParam.getServerTime();
        if (StringUtils.isEmpty(serverTime) || serverTime.contains("N")) {
            throw new XunyinException("请选择正常的时间段");
        }
        String pageId = tShareOrderParam.getPageId();
        int userId = tShareOrderParam.getUserId();
        int parentOrderId = tShareOrderParam.getParentOrderId();
        BigDecimal timeInterval = tShareOrderParam.getTimeInterval();
        //预订天数
        //int dateCount = tShareOrderParam.getDateCount();
        //是否选择使用会员时长
        //int memberTimelongFlag = tShareOrderParam.getMemberTimelongFlag();
        //会员拥有的总时长
        //Double memberTimeLong = tShareOrderParam.getMemberTimeLong();

        String userPhone = tShareOrderParam.getUserPhone();
        // 会员用户Id
        //Integer memberUserId = tShareOrderParam.getMemberUserId();

        //TStore tStore = tStoreService.getById(teaId);
        MtStore mtStore = storeService.queryStoreById(teaId);
        if (mtStore == null) {
            log.info("门店没有找到，teaId: {}", teaId);
            throw new XunyinException("门店没有找到");
        }
        MtStoreRoom mtStoreRoom = mtStoreRoomService.getById(teaChildId);
        //TStoreRoom tStoreRoom = tStoreRoomService.getById(teaChildId);
        if (mtStoreRoom == null) {
            log.info("房间没有找到，teaChildId: {}", teaChildId);
            throw new XunyinException("房间没有找到");
        }
        Long teaServerEndTime = tShareOrderMapper.findUserServerEndTime(teaId, teaChildId, userId);
        if (teaServerEndTime == null) {
            if (mtStoreRoom.getStoreRoomStatus().intValue() == StoreRoomStatusEnum.MODEL_TL.getKey()) {
                throw new XunyinException("房间待清洁，请稍后再预定");
            }
            if (mtStoreRoom.getStoreRoomStatus().intValue() == StoreRoomStatusEnum.USE.getKey()) {
                throw new XunyinException("房间使用中，请稍后再预定");
            }
            if (tShareOrderMapper.findUnServiceOrderCount(teaId, teaChildId) > 0) {
                throw new XunyinException("房间使用中，请稍后再预定");
            }
        }
        // JSONArray jsonarray = JSONArray.parseArray(times);
        //支付接口的订单号
        String appOrderNo = OrderNoUtil.getOrderNo("1011", "");
        //根据预订天数生成多笔订单 预约一天的情况
        /* if (dateCount == 1) {*/

        // i表示预定的小时数
        //double i = 0;
        //i = (jsonarray.size() - 1) * 0.5;
        BigDecimal storeRoomPrice = mtStoreRoom.getPrice();
        // 如果是会员，则需要按折扣价来算
        MtUserGrade mtUserGrade = mtUserGradeMapper.findUserGradeByUserId(userId);
        BigDecimal discount = new BigDecimal(1);
        if(mtUserGrade!=null){
            discount = new BigDecimal(Float.toString(mtUserGrade.getDiscount()));
            BigDecimal b01 = new BigDecimal("0.1");
            discount = discount.multiply(b01);
            storeRoomPrice = storeRoomPrice.multiply(discount);
        }
        // 计算订单金额
        BigDecimal orderMoney = storeRoomPrice.multiply(timeInterval);
        // 如果是续单，则用续单价格来计算订单金额
        if (tShareOrderParam.getIsRepeat() == 1) {
            orderMoney = mtStoreRoom.getRepeatPrice().multiply(timeInterval);
        }

        //orderMoney = orderMoney.multiply(BigDecimal.valueOf(dateCount));
        // BigDecimal orderMoney = new Double(mtStoreRoom.getPrice().doubleValue() * i * dateCount);

        // 表示选择的是套餐模式，订单金额按套餐金额计算
        if(tShareOrderParam.getPackMode()==0){
            orderMoney = tShareOrderParam.getPackMoney().multiply(discount);
        }
        // 实际支付金额，默认等于订单金额
        BigDecimal payMoney = orderMoney;
/*                double deductTimelong = 0.0;
                if (memberTimelongFlag == 0) {
                    payMoney = orderMoney;
                }*/

        //TMainCouponUser tMainCouponUser = null;
        MtUserCoupon userCoupon = null; // 优惠券信息
        MtUserCoupon userHourCoupon = null; // 小时卡券或次卡信息
        // 查看是否使用优惠券,根据优惠券Id获取优惠券信息
        if (tShareOrderParam.getUseCouponId() != null && tShareOrderParam.getUseCouponId() > 0) {
            //tMainCouponUser = tmainCouponUserMapper.selectById(tShareOrderParam.getUseCouponId());
            userCoupon = mtUserCouponMapper.selectById(tShareOrderParam.getUseCouponId());
        }

        // 是否使用小时卡券或次卡，根据小时卡券或次卡Id获取卡券信息
        if (tShareOrderParam.getUseHourCouponId() != null && tShareOrderParam.getUseHourCouponId() > 0) {
            userHourCoupon = mtUserCouponMapper.selectById(tShareOrderParam.getUseHourCouponId());
        }

        // 优惠券抵扣金额
        BigDecimal dedCouponMoney = new BigDecimal(0);

        // 如果有使用优惠券的情况下
        if (userCoupon != null) {
            if (userCoupon.getStatus().equals(StatusEnum.USED.getKey())) {
                throw new XunyinException("优惠券已使用过");
            }
            if (userCoupon.getStatus().equals(StatusEnum.EXPIRED.getKey())) {
                throw new XunyinException("优惠券已过期");
            }
            // 如果是优惠券判断是否消费预约满多少金额可用
            if (orderMoney.compareTo(userCoupon.getReachMoney()) >= 0) {
                // 如果优惠券金额大于等于订单金额，则支付金额为0
                if (userCoupon.getBalance().compareTo(orderMoney) >= 0) {

                    payMoney = new BigDecimal(0);
                    dedCouponMoney = orderMoney;

                    // 如果优惠券金额小于订单金额，则支付金额为订单金额-优惠券金额
                } else {
                    payMoney = orderMoney.subtract(userCoupon.getBalance());
                    dedCouponMoney = userCoupon.getBalance();
                    //payMoney = (int) (orderMoney - userCoupon.getAmount().intValue());
                }
            } else {
                throw new XunyinException("预约订单金额未达到使用优惠券条件，满" + userCoupon.getReachMoney() + "元可用");
            }
        }

        // 实际抵扣时长
        BigDecimal deductTimelong = new BigDecimal(0);
        // 小时卡或次卡抵扣金额
        BigDecimal hourCouponMoney = new BigDecimal(0);

        // 如果有使用小时卡券或次卡情况下
        if (userHourCoupon != null) {
            if (userHourCoupon.getStatus().equals(StatusEnum.EXPIRED.getKey())) {
                throw new XunyinException("卡券已过期");
            }
            // 如果是使用的小时卡券
            if (userHourCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())) {
                BigDecimal zeroBigDecimal = new BigDecimal(0);
                // 判断小时卡券的小时数是否已使用完
                if (userHourCoupon.getRemHourCount().compareTo(zeroBigDecimal) <= 0) {
                    throw new XunyinException("小时卡小时数已使用完");
                }

                // 获取小时卡券剩余时长对应的金额
                BigDecimal remHourMoney = new BigDecimal(0);
                remHourMoney = storeRoomPrice.multiply(userHourCoupon.getRemHourCount());
                //remHourMoney = orderMoney.multiply(BigDecimal.valueOf(dateCount));
                //int remHourMoney = new Double(mtStoreRoom.getPrice().doubleValue() * userHourCoupon.getRemHourCount() * dateCount).intValue();

                // 如果剩余时长对应的金额小于支付金额
                if (remHourMoney.compareTo(payMoney) < 0) {

                    deductTimelong = userHourCoupon.getRemHourCount();
                    BigDecimal tmpPayMoney = payMoney.subtract(remHourMoney);
                    payMoney = tmpPayMoney;

                // 如果剩余时长对应的金额大于等于支付金额
                } else {
                    log.info("storeRoomPrice={}, payMoney={}", storeRoomPrice, payMoney);
                    deductTimelong = payMoney.divide(storeRoomPrice);
                    payMoney = new BigDecimal(0);
                    //deductTimelong = new Double(payMoney/mtStoreRoom.getPrice().doubleValue()).intValue();
                    //payMoney = 0;

                }
                hourCouponMoney = remHourMoney;
            // 如果是使用的次卡
            } else if (userHourCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
                // 判断次数是否已使用完
                if (userHourCoupon.getRemUseableCount() <= 0) {

                    throw new XunyinException("次数卡的次数已使用完");

                // 获取次卡的每次抵扣时长
                } else {

                    // 获取每次可使用的小时数
                    int everyUseableHourCount = userHourCoupon.getEveryUseableHourCount();
                    BigDecimal everyHourCountMoney = storeRoomPrice.multiply(BigDecimal.valueOf(everyUseableHourCount));
                    // 如果对应的金额小于支付金额
                    if (everyHourCountMoney.compareTo(payMoney) < 0) {

                        BigDecimal tmpPayMoney = payMoney.subtract(everyHourCountMoney);
                        payMoney = tmpPayMoney;

                        // 如果对应的金额大于等于支付金额
                    } else {

                        payMoney = new BigDecimal(0);
                    }
                    deductTimelong = BigDecimal.valueOf(everyUseableHourCount);
                    hourCouponMoney = everyHourCountMoney;
                }
            }

        }


        //if(this.payType==0||this.payType==1){


        // 如果是平台通用余额支付
        if (tShareOrderParam.getPayType() == 0) {
            //SysXbuser sysXbuser = sysXbuserService.getById(tShareOrderParam.getUserId());
            //BigDecimal balance = sysXbuser.getBalance();
            // 实际支付金额是以分为计算，所以用户余额以元计算要*100
/*                    BigDecimal num100= new BigDecimal("100");
                    balance = balance.multiply(num100);*/
            YxUser userInfo = userService.getById(tShareOrderParam.getUserId());
            BigDecimal balance = userInfo.getNowMoney();
            // 用余额扣减支付金额，获取剩下的余额，更新用户余额
            BigDecimal surBalance = balance.subtract(payMoney);
            userInfo.setNowMoney(surBalance);
            userService.updateById(userInfo);
            //BigDecimal number = new BigDecimal(0);
            //number = BigDecimal.valueOf((int)surBalance);
            //number = BigDecimal.valueOf((int)surBalance).divide(num100);
            //sysXbuser.setBalance(BigDecimal.valueOf((int)surBalance).divide(num100));
            //sysXbuserService.updateById(sysXbuser);
        }

        // 如果是门店储值卡余额支付
        if (tShareOrderParam.getPayType() == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("storeId", tShareOrderParam.getStoreId());
            params.put("userId", tShareOrderParam.getUserId());
            List<MtUserBalance> userBalanceList = mtUserBalanceService.queryMtUserBalanceByParams(params);
            if (userBalanceList != null && userBalanceList.size() > 0) {

                MtUserBalance mtUserBalance = userBalanceList.get(0);
                if (mtUserBalance.getUserBalance().compareTo(payMoney) < 0) {
                    throw new XunyinException("门店储值卡余额不足");
                } else {
                    // 用余额扣减支付金额，获取剩下的余额，更新用户余额
                    BigDecimal surBalance = mtUserBalance.getUserBalance().subtract(payMoney);
                    mtUserBalance.setUserBalance(surBalance);
                    mtUserBalanceService.updateById(mtUserBalance);
                }
            } else {
                throw new XunyinException("门店储值卡余额不足");
            }
        }


        //获取订单号
        String orderNo = OrderNoUtil.getOrderNo("1010", "");
        //获取服务开始时间和结束时间
        //JSONObject serverStartTimeStr = (JSONObject) jsonarray.get(0);
        //Date serverStartTime = DateUtils.parseStrint2Date(serverStartTimeStr.getString("dateName") + " " + serverStartTimeStr.getString("timeName"), "yyyy-MM-dd HH:mm");
        if (serverTime != null && serverTime.contains(".")) {
            serverTime = serverTime.replaceAll("\\.", ":");
        }
        if (tShareOrderParam.getTeaServerStartTime() != null && tShareOrderParam.getTeaServerStartTime().contains(".")) {
            tShareOrderParam.setTeaServerStartTime(tShareOrderParam.getTeaServerStartTime().replaceAll("\\.", ":"));
        }
        if (tShareOrderParam.getTeaServerEndTime() != null && tShareOrderParam.getTeaServerEndTime().contains(".")) {
            tShareOrderParam.setTeaServerEndTime(tShareOrderParam.getTeaServerEndTime().replaceAll("\\.", ":"));
        }
        Date serverStartTime = DateUtils.parseStrint2Date(tShareOrderParam.getTeaServerStartTime(), "yyyy-MM-dd HH:mm");

        //JSONObject serverEntTimeStr = (JSONObject) jsonarray.get(jsonarray.size() - 1);
        //Date serverEndTime = DateUtils.parseStrint2Date(serverEntTimeStr.getString("dateName") + " " + serverEntTimeStr.getString("timeName"), "yyyy-MM-dd HH:mm");
        Date serverEndTime = DateUtils.parseStrint2Date(tShareOrderParam.getTeaServerEndTime(), "yyyy-MM-dd HH:mm");
        if (serverStartTime == null || serverEndTime == null) {
            throw new XunyinException("服务日期时间不正确 yyyy-MM-dd HH:mm");
        }
        if (teaServerEndTime != null ) {
            if (teaServerEndTime.longValue() * 1000L > serverStartTime.getTime()) {
                throw new XunyinException("只能选择" + DateUtils.secondToDate(teaServerEndTime.longValue()) + "到" + DateUtils.secondToDate(teaServerEndTime.longValue() + 1800L) + "之间的时间段");
            }
            if (serverStartTime.getTime() > (teaServerEndTime.longValue() * 1000L + 1800000L) ) {
                throw new XunyinException("只能选择" + DateUtils.secondToDate(teaServerEndTime.longValue()) + "到" + DateUtils.secondToDate(teaServerEndTime.longValue() + 1800L) + "之间的时间段");
            }
        } else {
            if ((serverStartTime.getTime() - System.currentTimeMillis())/1000L > 1800L) {
                throw new XunyinException("只能选择30分钟内的开始时间");
            }
        }
        //生成订单
        TShareOrder teaOrder = new TShareOrder();
        //teaOrder.setMainId(mtStore.getMainId());
        teaOrder.setAreaId(Integer.valueOf(mtStore.getCountyCode()));
        teaOrder.setOrderTime(nowDate);
        teaOrder.setOrderNo(orderNo);
        teaOrder.setAppUserId(appUserId);
        teaOrder.setAppType(1);
        teaOrder.setStoreId(teaId);
        teaOrder.setStoreName(mtStore.getName());
        teaOrder.setStoreRoomId(teaChildId);
        teaOrder.setStoreRoomName(mtStoreRoom.getStoreRoomName());
        teaOrder.setTeaSubscribeTimes(tShareOrderParam.getTeaSubscribeTimes());
        teaOrder.setTeaServerTime(serverTime);
        teaOrder.setTeaServerStartTime(serverStartTime);
        teaOrder.setTeaServerEndTime(serverEndTime);
        teaOrder.setParentOrderId(parentOrderId);
        teaOrder.setAppOrderNo(appOrderNo);
        teaOrder.setResultFlag(ResultFlag.WAIT_PAY.getValue());
        teaOrder.setPayType(Integer.valueOf(tShareOrderParam.getPayType()));
        teaOrder.setOrderMondey(orderMoney);
        teaOrder.setPayMoney(payMoney);
        teaOrder.setPageId(pageId);
        teaOrder.setServiceStatus(0);
        teaOrder.setSettleFlag(0);
        teaOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.getValue());
/*                if (tMainCouponUser != null) {
                    teaOrder.setDiscountId(tMainCouponUser.getId());
                    teaOrder.setDiscountType(tMainCouponUser.getDeductionType());
                    teaOrder.setDiscountQuota(tMainCouponUser.getDeductionNum().intValue());
                }*/
        teaOrder.setTimeInterval(tShareOrderParam.getTimeInterval());
        teaOrder.setCreateTime(nowDate);
        teaOrder.setCreateUserId(userId);
        teaOrder.setStatus(CommonConst.ENABLE_FLAG);
        teaOrder.setUserPhone(userPhone);
        teaOrder.setDeductTimelong(deductTimelong);
        teaOrder.setUseCouponId(tShareOrderParam.getUseCouponId());
        teaOrder.setCouponMoney(dedCouponMoney);
        teaOrder.setHourNum(deductTimelong);
        teaOrder.setHourCouponMoney(hourCouponMoney);
        teaOrder.setUseHourCouponId(tShareOrderParam.getUseHourCouponId());
        tShareOrderMapper.insert(teaOrder);

        shareOrderList.add(teaOrder);


        return shareOrderList;


    }

    /**
     * 已支付退款情况下，预约订单处理
     * @param orderInfo
     */
    @Override
    public void refundProcess(TShareOrder orderInfo) {
        TShareOrder order = new TShareOrder();
        Date nowDate = new Date();
        // 订单状态改为取消
        order.setId(orderInfo.getId());
        order.setServiceStatus(5);
        order.setOrderStatus(OrderStatusEnum.CANCELLED.getIndex());
        order.setUpdateUserId(orderInfo.getCreateUserId());
        order.setUpdateTime(nowDate);

        tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                .eq(TShareOrder::getId, orderInfo.getId()));
        // 如果是平台通用余额支付,则加回通用余额
        if (orderInfo.getPayType() == 0) {

            YxUser userInfo = userService.getById(orderInfo.getCreateUserId());
            BigDecimal balance = userInfo.getNowMoney();
            // 用余额扣减支付金额，获取剩下的余额，更新用户余额
            BigDecimal surBalance = balance.add(orderInfo.getPayMoney());
            userInfo.setNowMoney(surBalance);
            userService.updateById(userInfo);
        }

        // 如果是门店储值卡余额支付,则加回门店储值卡余额
        if (orderInfo.getPayType() == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("storeId", orderInfo.getStoreId());
            params.put("userId", orderInfo.getCreateUserId());
            List<MtUserBalance> userBalanceList = mtUserBalanceService.queryMtUserBalanceByParams(params);
            if (userBalanceList != null && userBalanceList.size() > 0) {

                //加回对应订单使用的门店储值卡的具体余额
                MtUserBalance mtUserBalance = userBalanceList.get(0);
                BigDecimal surBalance = mtUserBalance.getUserBalance().add(orderInfo.getPayMoney());
                mtUserBalance.setUserBalance(surBalance);
                mtUserBalanceService.updateById(mtUserBalance);
            } else {
                throw new XunyinException("找不到门店储值卡余额账户");
            }
        }

        // 如果有使用优惠券与卡券，则退回给用户
        this.refundConpon(orderInfo);
    }

    /**
     * 已支付退款情况下，如果有使用优惠券与卡券，则退回给用户
     * @param orderInfo
     */
    public void refundConpon(TShareOrder orderInfo) {

        // 如果有使用优惠券,则把抵扣的优惠券还原未使用状态
        if (orderInfo.getUseCouponId() != null && orderInfo.getUseCouponId() > 0) {
            MtUserCoupon mtUserCoupon = new MtUserCoupon();
            mtUserCoupon.setId(orderInfo.getUseCouponId());
            mtUserCoupon.setStatus(StatusEnum.ENABLED.getKey());
            mtUserCoupon.setUsedTime(null);
            mtUserCouponMapper.update(mtUserCoupon, Wrappers.<MtUserCoupon>lambdaQuery()
                    .eq(MtUserCoupon::getId, mtUserCoupon.getId()));

        }

        // 如果有使用卡券（小时卡、次数卡）,则还原抵扣（小时卡、次数卡）小时数或次数还原
        if (orderInfo.getUseHourCouponId() != null && orderInfo.getUseHourCouponId() > 0) {
            MtUserCoupon hourCoupon = mtUserCouponMapper.selectById(orderInfo.getUseHourCouponId());
            //Boolean usedFlag = false;
            // 如果使用小时卡,则把对应的小时卡券剩余的小时数+订单使用的小时数
            if (hourCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())) {
                BigDecimal remHourCount = hourCoupon.getRemHourCount().add(orderInfo.getHourNum());
                BigDecimal zeroBigDecimal = new BigDecimal(0);
                hourCoupon.setStatus(StatusEnum.ENABLED.getKey());
/*                if(remHourCount.compareTo(zeroBigDecimal)<=0){
                    //usedFlag = true;
                    hourCoupon.setStatus(StatusEnum.USED.getKey());
                }*/
                hourCoupon.setRemHourCount(remHourCount);
            }
            // 如果使用次数卡,则把对应的次数卡剩余的次数+当前订单使用的次数1
            if (hourCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
                int remUseableCount = hourCoupon.getRemUseableCount() + 1;
                hourCoupon.setStatus(StatusEnum.ENABLED.getKey());
/*                if(remUseableCount<=0){
                    hourCoupon.setStatus(StatusEnum.USED.getKey());
                }*/
                hourCoupon.setRemUseableCount(remUseableCount);
            }
            //hourCoupon.setUsedTime(new Date());
            mtUserCouponMapper.update(hourCoupon, Wrappers.<MtUserCoupon>lambdaQuery()
                    .eq(MtUserCoupon::getId, hourCoupon.getId()));
        }

    }

    /**
     * 预约订单支付完成回调
     * @param orderInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(TShareOrder orderInfo) {
        log.info("=====支付完成回调=====");
        try {
            TShareOrder updateTeaOrder = new TShareOrder();
            updateTeaOrder.setId(orderInfo.getId());
            updateTeaOrder.setResultFlag(ResultFlag.PAID.getValue());
            updateTeaOrder.setPayTime(new Date());
/*            if (orderInfo.getParentOrderId() != 0) {
                updateTeaOrder.setOrderStatus(OrderStatusEnum.IN_SERVICE.getValue());
            } else {
                updateTeaOrder.setOrderStatus(OrderStatusEnum.PAID.getValue());
            }*/

            updateTeaOrder.setOrderStatus(OrderStatusEnum.PAID.getValue());
            updateTeaOrder.setTransactionId(orderInfo.getTransactionId());
            updateTeaOrder.setUpdateTime(new Date());
            tShareOrderMapper.update(updateTeaOrder, Wrappers.<TShareOrder>lambdaQuery()
                    .eq(TShareOrder::getId, orderInfo.getId()));

            log.info("订单修改成功,支付订单号outTradeNo：{}", orderInfo.getAppOrderNo());

            // redis发送消息队列
            // 用户下单支付完成后，判断是否为第一单，如果是，看是否有推荐人
            // 如果有，看门店是否有设置推荐赠送时长券，如果有就发送一个推荐赠送的时长券给推荐人
            PublishMessage publishMessage = new PublishMessage();
            publishMessage.setMsgType(3);
            publishMessage.setStoreId(orderInfo.getStoreId());
            publishMessage.setUserId(orderInfo.getCreateUserId());
            redisSqueueService.doSomethingAndPublishMessage(publishMessage);

            // 如果有使用优惠券,则把对应的优惠券状态改为已使用
            if (orderInfo.getUseCouponId() != null && orderInfo.getUseCouponId() > 0) {
                MtUserCoupon mtUserCoupon = new MtUserCoupon();
                mtUserCoupon.setId(orderInfo.getUseCouponId());
                mtUserCoupon.setStatus(StatusEnum.USED.getKey());
                mtUserCoupon.setUsedTime(new Date());
                mtUserCouponMapper.update(mtUserCoupon, Wrappers.<MtUserCoupon>lambdaQuery()
                        .eq(MtUserCoupon::getId, mtUserCoupon.getId()));

            }

            if (orderInfo.getUseHourCouponId() != null && orderInfo.getUseHourCouponId() > 0) {
                MtUserCoupon hourCoupon = mtUserCouponMapper.selectById(orderInfo.getUseHourCouponId());
                //Boolean usedFlag = false;
                // 如果使用小时卡,则把对应的小时卡券剩余的小时数-订单使用的小时数
                if (hourCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())) {
                    //BigDecimal remHourCount = hourCoupon.getRemHourCount().subtract(updateTeaOrder.getHourNum());
                    BigDecimal remHourCount = hourCoupon.getRemHourCount().subtract(orderInfo.getHourNum());
                    BigDecimal zeroBigDecimal = new BigDecimal(0);
                    if (remHourCount.compareTo(zeroBigDecimal) <= 0) {
                        //usedFlag = true;
                        hourCoupon.setStatus(StatusEnum.USED.getKey());
                    }
                    hourCoupon.setRemHourCount(remHourCount);
                }
                // 如果使用次数卡,则把对应的次数卡剩余的次数-当前订单使用的次数1
                if (hourCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
                    int remUseableCount = hourCoupon.getRemUseableCount() - 1;
                    if (remUseableCount <= 0) {
                        hourCoupon.setStatus(StatusEnum.USED.getKey());
                    }
                    hourCoupon.setRemUseableCount(remUseableCount);
                }
                hourCoupon.setUsedTime(new Date());
                mtUserCouponMapper.update(hourCoupon, Wrappers.<MtUserCoupon>lambdaQuery()
                        .eq(MtUserCoupon::getId, hourCoupon.getId()));
            }

            // 添加优惠券、卡券（小时卡，次卡）流水记录（待完善）


            //查看是否使用优惠券-有的话就扣除
/*                if (orderInfo.getDiscountId() != null) {
                    TMainCouponUser teaMainCouponUser = new TMainCouponUser();
                    teaMainCouponUser.setId(orderInfo.getDiscountId());
                    teaMainCouponUser.setUseStatus(CommonConst.ORDER_SERVICE);
                    teaMainCouponUser.setUseTime(new Date());
                    tmainCouponUserMapper.update(teaMainCouponUser, Wrappers.<TMainCouponUser>lambdaQuery()
                            .eq(TMainCouponUser::getId, teaMainCouponUser.getId()));
                }*/

            //记录时长使用日志
/*                if (orderInfo.getDeductTimelong().intValue() > 0) {
                    TimelongRecord timelongRecord = new TimelongRecord();
                    timelongRecord.setMainId(orderInfo.getMainId());
                    timelongRecord.setSource(3);
                    timelongRecord.setTimelong(orderInfo.getDeductTimelong());
                    timelongRecord.setGiver(orderInfo.getMemberUserId());
                    timelongRecord.setRecipient(0);
                    timelongRecord.setOrderNo(orderInfo.getOrderNo());
                    timelongRecord.setRemark("订单支付-部分使用时长");
                    timelongRecord.setCreateUserId(orderInfo.getCreateUserId());
                    timelongRecord.setCreateTime(new Date());
                    timelongRecord.setStatus(Short.parseShort("1"));
                    timelongRecordMapper.insert(timelongRecord);
                    // 扣减会员卡中的时长
                    //deductMembersTimelong(orderInfo.getMainId(), orderInfo.getUserPhone(), orderInfo.getDeductTimelong().doubleValue());
                }*/

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     *  创建充值订单
     *  @param tShareOrderParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TRechargeOrder createRechargeOrder(TShareOrderParam tShareOrderParam) {
        Date nowDate = new Date();
        TRechargeOrder record = null;
        String orderNo = null;
        try {
            //生成订单号
            if (tShareOrderParam.getOrderNo() == null || "".equals(tShareOrderParam.getOrderNo())) {
                orderNo = OrderNoUtil.getOrderNo("1012", "");//获取订单号
            }
            //生成订单号
            // String orderNo = OrderNoUtil.getOrderNo("1012", ""); //获取订单号
            //获取前端参数
            String appUserId = tShareOrderParam.getOpenId();
            String userPhone = tShareOrderParam.getUserPhone();
            String pageId = tShareOrderParam.getPageId();
            int rechargeSetId = tShareOrderParam.getRechargeSetId();
            int teaHouseId = tShareOrderParam.getTeaHouseId();
            //获取商品信息
            TRechargeSet stRechargeSet = tRechargeSetMapper.selectById(rechargeSetId);
            if (stRechargeSet == null) {
                log.error("stRechargeSet not exist,stRechargeSetId={}", rechargeSetId);
                //return CommonUtil.errorJson(ErrorEnum.E_100017);
            }
            TStore tStore = tStoreService.getById(teaHouseId);
            //JSONObject tea = teaHouseDao.getTeaInfoById(teaHouseId);
            if (tStore == null) {
                log.info("会客厅(门店)没有找到，teaId: {}", teaHouseId);
            }
            int orderMoney = stRechargeSet.getPrice();
            //是否可折扣商品
            record = new TRechargeOrder();
            record.setRechargeSetId(rechargeSetId);
            record.setRechargeSetName(stRechargeSet.getName());
            record.setAllDiscountMoney(0);
            record.setAppOrderNo(orderNo);
            record.setOrderNo(orderNo);
            record.setAppType(1);
            record.setAppUserId(appUserId);
            record.setCreateTime(nowDate);
            record.setCreateUserId(0);
            record.setOrderMoney(orderMoney);
            record.setPayMoney(orderMoney);
            record.setOrderStatus(CommonConst.DISABLE_FLAG);
            record.setResultFlag(ResultFlag.WAIT_PAY.getValue());
            record.setPageId(pageId);
            record.setOrderTime(nowDate);
            record.setPayType(0);
            record.setStatus(CommonConst.ENABLE_FLAG);
            record.setPhone(userPhone);
            record.setTeaHouseId(teaHouseId);
            record.setMainId(tStore.getMainId());
            record.setTeaHouseName(tStore.getName());
            tRechargeOrderMapper.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return record;
    }

    //实现日期加一天的方法
    public static String addDay(String s, int n) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(s));
            //增加一天
            if (n >= 1) {
                n = 1;
            }
            cd.add(Calendar.DATE, n);
            return sdf.format(cd.getTime());

        } catch (Exception e) {
            return null;
        }
    }

    //扣减会员卡中的时长
    @Override
    public void deductMembersTimelong(Integer mainId, String memberUserPhone, Double deductTimelong, Double memberTimeLong) {
        TMembersUser teaMembersUser = new TMembersUser();
        teaMembersUser.setMainId(mainId);
        teaMembersUser.setMemberUserPhone(memberUserPhone);
        //set members_time_length = members_time_length - #{membersTimeLength,jdbcType=DOUBLE},
        //MemberUserVo memberUserVo = tMembersUserMapper.selectByTransPhoneAndMainId(memberUserPhone, mainId);
        //BigDecimal membersTimeLength =
/*        Double membersTimeLength = memberTimeLong - deductTimelong;
        if(membersTimeLength<0.0){
            membersTimeLength = 0.0;
        }*/
        BigDecimal b1 = new BigDecimal(memberTimeLong.toString());
        BigDecimal b2 = new BigDecimal(deductTimelong.toString());
        BigDecimal membersTimeLength = b1.subtract(b2);
        BigDecimal zero = new BigDecimal(0);
        if (membersTimeLength.compareTo(zero) < 0) {
            membersTimeLength = new BigDecimal(0);
        }
        teaMembersUser.setMembersTimeLength(membersTimeLength);
        teaMembersUser.setUpdateTime(new Date());
        tMembersUserMapper.update(teaMembersUser, Wrappers.<TMembersUser>lambdaQuery()
                .eq(TMembersUser::getMainId, teaMembersUser.getMainId())
                .eq(TMembersUser::getMemberUserPhone, teaMembersUser.getMemberUserPhone()));

    }

    @Override
    public void insertIntoRecord(TShareOrderParam tShareOrderParam) {
        TShareOrder teaOrder = tShareOrderMapper.selectById(tShareOrderParam.getOrderId());
        TCleaningRecord tCleaningRecord = new TCleaningRecord();
        tCleaningRecord.setStoreId(tShareOrderParam.getStoreId());
        tCleaningRecord.setTeaChildId(tShareOrderParam.getStoreRoomId());
        tCleaningRecord.setTeaChildName(tShareOrderParam.getStoreRoomName());
        // tCleaningRecord.setPictures(tShareOrderParam.getPictures());
        tCleaningRecord.setCleannerPhone(tShareOrderParam.getCleannerPhone());
        tCleaningRecord.setRemark(tShareOrderParam.getRemark());
        tCleaningRecord.setCreateTime(new Date());
        tCleaningRecord.setOrderId(tShareOrderParam.getOrderId());
        tCleaningRecordMapper.insert(tCleaningRecord);

        // 修改订单服务状态为已清洁
        teaOrder.setServiceStatus(9);
        tShareOrderMapper.update(teaOrder, Wrappers.<TShareOrder>lambdaQuery()
                .eq(TShareOrder::getId, tShareOrderParam.getOrderId()));

        // 修改房间服务状态为已清洁（空闲中）
        MtStoreRoom mtStoreRoom = new MtStoreRoom();
        mtStoreRoom.setStoreRoomStatus(StoreRoomStatusEnum.IDLE.getKey());
        mtStoreRoomMapper.update(mtStoreRoom, Wrappers.<MtStoreRoom>lambdaQuery()
                .eq(MtStoreRoom::getId, tShareOrderParam.getStoreRoomId()));
    }

    /**
     * 根据包间分类统计订单占比
     *
     * @return OrderCountDto
     */
    @Override
    public ShareOrderCountDto getOrderCount(Integer storeId) {

        // 表示平台登录，不是门店登录
        if (storeId <= 0) {
            storeId = null;
        }

        //获取所有订单转态为已支付的
        List<ShareCountDto> nameList = mtStoreRoomService.findRoomName(storeId);
        Map<String, Integer> childrenMap = new HashMap<>();
        nameList.forEach(i -> {
            if (i != null) {
                if (childrenMap.containsKey(i.getRoomName())) {
                    childrenMap.put(i.getRoomName(), childrenMap.get(i.getRoomName()) + 1);
                } else {
                    childrenMap.put(i.getRoomName(), 1);
                }
            }
        });
        List<ShareOrderCountDto.ShareOrderCountData> list = new ArrayList<>();
        List<String> columns = new ArrayList<>();
        childrenMap.forEach((k, v) -> {
            ShareOrderCountDto.ShareOrderCountData orderCountData = new ShareOrderCountDto.ShareOrderCountData();
            orderCountData.setName(k);
            orderCountData.setValue(v);
            columns.add(k);
            list.add(orderCountData);
        });
        ShareOrderCountDto orderCountDto = new ShareOrderCountDto();
        orderCountDto.setColumn(columns);
        orderCountDto.setOrderCountDatas(list);
        return orderCountDto;
    }

    /**
     * 返回本月订单金额与数量
     *
     * @return map
     */
    @Override
    public Map<String, Object> chartCount(Integer storeId) {
        Map<String, Object> map = new LinkedHashMap<>();
        //Date nowMonth = DateUtil.beginOfMonth(new Date());
        Date nowMonth = cn.hutool.core.date.DateUtil.beginOfMonth(new Date());
        // 表示平台登录，不是门店登录
        if (storeId <= 0) {
            storeId = null;
        }
        map.put("chart", tShareOrderMapper.chartList(nowMonth, storeId));
        map.put("chartT", tShareOrderMapper.chartListT(nowMonth, storeId));

        return map;
    }

}
